package com.hxkcloud.nurse.activitys;

import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.os.Message;
import android.support.v7.widget.LinearLayoutManager;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.TextView;
import android.widget.Toast;

import com.hxkcloud.nurse.R;
import com.hxkcloud.nurse.adapter.DetailListAdapter;
import com.hxkcloud.nurse.adapter.Kind1Apater;
import com.hxkcloud.nurse.beans.DepartmentBean;
import com.hxkcloud.nurse.beans.DiseaseBean;
import com.hxkcloud.nurse.beans.PointBean;
import com.hxkcloud.nurse.dborm.DepartmentDao;
import com.hxkcloud.nurse.dborm.DiseaseDao;
import com.hxkcloud.nurse.utils.BrightnessUtils;
import com.hxkcloud.nurse.views.ListDividerItemDecoration;
import com.hxkcloud.nurse.views.pulltorefreshlayout.PullToRefreshLayout;
import com.hxkcloud.nurse.views.pulltorefreshlayout.PullableRecyclerView;

import java.util.ArrayList;
import java.util.List;

import lecho.lib.hellocharts.animation.ChartAnimationListener;
import lecho.lib.hellocharts.listener.LineChartOnValueSelectListener;
import lecho.lib.hellocharts.model.Axis;
import lecho.lib.hellocharts.model.AxisValue;
import lecho.lib.hellocharts.model.Line;
import lecho.lib.hellocharts.model.LineChartData;
import lecho.lib.hellocharts.model.PointValue;
import lecho.lib.hellocharts.model.ValueShape;
import lecho.lib.hellocharts.model.Viewport;
import lecho.lib.hellocharts.util.ChartUtils;
import lecho.lib.hellocharts.view.Chart;
import lecho.lib.hellocharts.view.LineChartView;

/**
 * Created by ray_lei on 2016/7/10.
 */
public class XuetangDetailActivity extends BaseActivity implements View.OnClickListener {

    private LinearLayout ll_title;
    private ImageView iv_back;
    private TextView tv_title;

    private LinearLayout ivgLayout;
    private LinearLayout timeLayout;
    private LinearLayout catLayout;
    private TextView timeTV;//时间
    private TextView catTV;//类别
    private ImageView timeIV;
    private ImageView catIV;


    private LineChartView chart;
    private LineChartData data;
    private int numberOfLines = 1;
    private int maxNumberOfLines = 4;
    private int numberOfPoints = 5;

    float[][] randomNumbersTab = new float[maxNumberOfLines][numberOfPoints];

    private boolean hasAxes = true;
    private boolean hasAxesNames = true;
    private boolean hasLines = true;
    private boolean hasPoints = true;
    private ValueShape shape = ValueShape.CIRCLE;
    private boolean isFilled = false;
    private boolean hasLabels = false;
    private boolean isCubic = false;
    private boolean hasLabelForSelected = false;
    private boolean pointsHaveDifferentColor;

    private PullToRefreshLayout refreshLayout;
    private PullableRecyclerView recycleView;

    private List<PointBean> stringList;
    private DetailListAdapter adapter;

    private PopupWindow timePopup;//选择全部
//    private Button dayBtn;
    private Button weekBtn;
    private Button monthBtn;
    private View timeWholeView;

    private PopupWindow kindPopup;//类别
    private ListView kindListView;
    private Kind1Apater kindAdapter;

    private View kindWholeView;

    @Override
    protected void updateByHandler(Message msg) {
        switch (msg.what) {

        }
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_layout_xuetangdetail);
        stringList = new ArrayList<PointBean>();

        chart = (LineChartView) findViewById(R.id.xuetangdetail_chart);

        ll_title = (LinearLayout) findViewById(R.id.ll_title);
        iv_back = (ImageView) findViewById(R.id.iv_title_back);
        tv_title = (TextView) findViewById(R.id.tv_title_title);

        setTitlePadding(ll_title);
        iv_back.setVisibility(View.VISIBLE);
        iv_back.setOnClickListener(this);
        tv_title.setText(getResources().getText(R.string.montitor_xuetang_text));

        // chart
        generateValues();
        generateData();
        chart.setViewportCalculationEnabled(false);
        resetViewport();

        refreshLayout = (PullToRefreshLayout) findViewById(R.id.xuetangdetail_refreshlayout);
        recycleView = (PullableRecyclerView) findViewById(R.id.xuetangdetail_recyclerview);

        LinearLayoutManager mLayoutManager = new LinearLayoutManager(this);
        mLayoutManager.setOrientation(LinearLayoutManager.VERTICAL);
        recycleView.setLayoutManager(mLayoutManager);
        ListDividerItemDecoration itemDecoration = new ListDividerItemDecoration(
                this, ListDividerItemDecoration.VERTICAL_LIST);
        recycleView.addItemDecoration(itemDecoration);

        adapter = new DetailListAdapter(this, stringList, recycleView,loginInfo.getUserStyle());
        recycleView.setAdapter(adapter);

        initView();
        initData();
        initListener();


    }

    @Override
    protected void initView() {
        ivgLayout = (LinearLayout) findViewById(R.id.xuetangdetail_layout_ivg);

        timeLayout = (LinearLayout) findViewById(R.id.xuetangdetail_layout_time);
        catLayout = (LinearLayout) findViewById(R.id.xuetangdetail_layout_cat);
        timeTV = (TextView) findViewById(R.id.xuetangdetail_tv_time);
        catTV = (TextView) findViewById(R.id.xuetangdetail_tv_cat);
        timeIV = (ImageView) findViewById(R.id.xuetangdetail_iv_time);
        catIV = (ImageView) findViewById(R.id.xuetangdetail_iv_cat);
    }

    @Override
    protected void initListener() {
        timeLayout.setOnClickListener(this);
        catLayout.setOnClickListener(this);
        kindWholeView.setOnClickListener(this);
        timeWholeView.setOnClickListener(this);
    }

    @Override
    protected void initData() {
        initTimePopup();
        initKindPopup();
    }

    private void setInitPopup() {

        timeTV.setTextColor(mContext.getResources().getColor(R.color.black_text));
        timeIV.setImageResource(R.mipmap.tab_arrow);

        catTV.setTextColor(mContext.getResources().getColor(R.color.black_text));
        catIV.setImageResource(R.mipmap.tab_arrow);
    }

    private void initTimePopup() {
        timePopup = new PopupWindow(this);
        View timeView = LayoutInflater.from(this).inflate(R.layout.popup_layout_timeline, null);
        timePopup.setContentView(timeView);

        timePopup.setWidth(screenWidth);
        timePopup.setHeight(ViewGroup.LayoutParams.WRAP_CONTENT);
        timePopup.setFocusable(true);
        timePopup.setTouchable(true);
        timePopup.setOutsideTouchable(true);
        timePopup.setBackgroundDrawable(new ColorDrawable(0x00000000));


//        dayBtn = (Button) timeView.findViewById(R.id.timeline_btn_day);
        monthBtn = (Button) timeView.findViewById(R.id.timeline_btn_month);
        weekBtn = (Button) timeView.findViewById(R.id.timeline_btn_week);
        timeWholeView = (View) timeView.findViewById(R.id.timeline_view_whole);

//        dayBtn.setOnClickListener(this);
        weekBtn.setOnClickListener(this);
        monthBtn.setOnClickListener(this);
        ;
        timeWholeView.setOnClickListener(this);

        timePopup.setOnDismissListener(new PopupWindow.OnDismissListener() {
            @Override
            public void onDismiss() {
                BrightnessUtils.lightOn(XuetangDetailActivity.this);
            }
        });
    }


    private void initKindPopup() {
        kindPopup = new PopupWindow(this);
        View kindView = LayoutInflater.from(this).inflate(R.layout.popup_layout_kind, null);
        kindPopup.setContentView(kindView);

        kindPopup.setWidth(screenWidth);
        kindPopup.setHeight(ViewGroup.LayoutParams.WRAP_CONTENT);
        kindPopup.setFocusable(true);
        kindPopup.setTouchable(true);
        kindPopup.setOutsideTouchable(true);
        kindPopup.setBackgroundDrawable(new ColorDrawable(0x00000000));

//        List<String> kinds = new ArrayList<String>();
//        kinds.add("空腹(餐前)");
//        kinds.add("餐后1小时");
//        kinds.add("餐后2小时");
//        kinds.add("睡前");
        DiseaseDao dao = new DiseaseDao(mContext);
        String departmentId = loginInfo.getDepartmentId();
        DepartmentDao departmentDao = new DepartmentDao(mContext);
        for (DepartmentBean departmentBean : departmentDao.getDepartment()) {
            if ((departmentBean.getDepartmentId() + "").equals(departmentId)) {
                if (departmentBean.getType().equals("0")) {//chanke
                    departmentId = "-1";
                    break;
                }
            }
        }
        List<DiseaseBean> beans = dao.getDisease(departmentId);

        kindListView = (ListView) kindView.findViewById(R.id.kind_listview);
        kindAdapter = new Kind1Apater(this, beans);
        kindListView.setAdapter(kindAdapter);
        kindListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                kindPopup.dismiss();
            }
        });
        kindWholeView = (View) kindView.findViewById(R.id.kind_view_whole);

        kindPopup.setOnDismissListener(new PopupWindow.OnDismissListener() {
            @Override
            public void onDismiss() {
//                BrightnessUtils.lightOn(getActivity());
            }
        });
    }


    private void generateValues() {
        for (int i = 0; i < maxNumberOfLines; ++i) {
            for (int j = 0; j < numberOfPoints; ++j) {
                randomNumbersTab[i][j] = (float) Math.random() * 10f;
            }
        }
    }

    private void reset() {
        numberOfLines = 1;

        hasAxes = true;
        hasAxesNames = true;
        hasLines = true;
        hasPoints = true;
        shape = ValueShape.CIRCLE;
        isFilled = false;
        hasLabels = false;
        isCubic = false;
        hasLabelForSelected = false;
        pointsHaveDifferentColor = false;

        chart.setValueSelectionEnabled(hasLabelForSelected);
        resetViewport();
    }


    private void resetViewport() {
        // Reset viewport height range to (0,100)
        final Viewport v = new Viewport(chart.getMaximumViewport());
        v.bottom = 0;
        v.top = 10;
        v.left = 0;
        v.right = numberOfPoints - 1;
        chart.setMaximumViewport(v);
        chart.setCurrentViewport(v);
    }


    private void generateData() {

        List<Line> lines = new ArrayList<Line>();
        for (int i = 0; i < numberOfLines; ++i) {

            List<PointValue> values = new ArrayList<PointValue>();
//                for (int j = 0; j < numberOfPoints; ++j) {
//                    PointValue point =new PointValue(j, randomNumbersTab[i][j]);
//                    if(j%2==0){
//                        //修改了PointValue，LineChartRenderer
//                        point.setBig(true);
//                    }
//                    values.add(point);
//                }
            values.add(new PointValue(0, 2));
            values.add(new PointValue(1, 8));
            PointValue point = new PointValue(2, 1);
            point.setBig(true);
            values.add(point);
            values.add(new PointValue(3, 6));

            Line line = new Line(values);
            line.setColor(ChartUtils.COLORS[i]);
            line.setShape(shape);
            line.setCubic(isCubic);
            line.setFilled(isFilled);
            line.setHasLabels(hasLabels);
            line.setHasLabelsOnlyForSelected(hasLabelForSelected);
            line.setHasLines(hasLines);
            line.setHasPoints(hasPoints);
            if (pointsHaveDifferentColor) {
                line.setPointColor(ChartUtils.COLORS[(i + 1) % ChartUtils.COLORS.length]);
            }
            lines.add(line);
        }

        data = new LineChartData(lines);

        if (hasAxes) {
            List<AxisValue> mAxisValues = new ArrayList<AxisValue>();
            mAxisValues.add(new AxisValue(0).setLabel("06:00")); //为每个对应的i设置相应的label(显示在X轴)
            mAxisValues.add(new AxisValue(1).setLabel("12:00"));
            mAxisValues.add(new AxisValue(2).setLabel("18:00"));
            mAxisValues.add(new AxisValue(3).setLabel("24:00"));

            Axis axisX = new Axis(mAxisValues);

            List<AxisValue> yAxisValues = new ArrayList<AxisValue>();
            yAxisValues.add(new AxisValue(2).setLabel("02")); //为每个对应的i设置相应的label(显示在X轴)
            yAxisValues.add(new AxisValue(4).setLabel("04"));
            yAxisValues.add(new AxisValue(6).setLabel("06"));
            yAxisValues.add(new AxisValue(8).setLabel("08"));
            yAxisValues.add(new AxisValue(10).setLabel("10"));

            Axis axisY = new Axis(yAxisValues).setHasLines(true);
            if (hasAxesNames) {
//                    axisX.setName("Axis X");
//                    axisY.setName("Axis Y");
            }
            data.setAxisXBottom(axisX);
            data.setAxisYLeft(axisY);
        } else {
            data.setAxisXBottom(null);
            data.setAxisYLeft(null);
        }

//            data.setBaseValue(Float.NEGATIVE_INFINITY);
        chart.setLineChartData(data);

    }


    /**
     * Adds lines to data, after that data should be set again with
     * {@link LineChartView#setLineChartData(LineChartData)}. Last 4th line has non-monotonically x values.
     */
    private void addLineToData() {
        if (data.getLines().size() >= maxNumberOfLines) {
            Toast.makeText(this, "Samples app uses max 4 lines!", Toast.LENGTH_SHORT).show();
            return;
        } else {
            ++numberOfLines;
        }

        generateData();
    }

    private void toggleLines() {
        hasLines = !hasLines;

        generateData();
    }

    private void togglePoints() {
        hasPoints = !hasPoints;

        generateData();
    }

    private void toggleCubic() {
        isCubic = !isCubic;

        generateData();

        if (isCubic) {
            // It is good idea to manually set a little higher max viewport for cubic lines because sometimes line
            // go above or below max/min. To do that use Viewport.inest() method and pass negative value as dy
            // parameter or just set top and bottom values manually.
            // In this example I know that Y values are within (0,100) range so I set viewport height range manually
            // to (-5, 105).
            // To make this works during animations you should use Chart.setViewportCalculationEnabled(false) before
            // modifying viewport.
            // Remember to set viewport after you call setLineChartData().
            final Viewport v = new Viewport(chart.getMaximumViewport());
            v.bottom = -5;
            v.top = 105;
            // You have to set max and current viewports separately.
            chart.setMaximumViewport(v);
            // I changing current viewport with animation in this case.
            chart.setCurrentViewportWithAnimation(v);
        } else {
            // If not cubic restore viewport to (0,100) range.
            final Viewport v = new Viewport(chart.getMaximumViewport());
            v.bottom = 0;
            v.top = 100;

            // You have to set max and current viewports separately.
            // In this case, if I want animation I have to set current viewport first and use animation listener.
            // Max viewport will be set in onAnimationFinished method.
            chart.setViewportAnimationListener(new ChartAnimationListener() {

                @Override
                public void onAnimationStarted() {
                    // TODO Auto-generated method stub

                }

                @Override
                public void onAnimationFinished() {
                    // Set max viewpirt and remove listener.
                    chart.setMaximumViewport(v);
                    chart.setViewportAnimationListener(null);

                }
            });
            // Set current viewpirt with animation;
            chart.setCurrentViewportWithAnimation(v);
        }

    }

    private void toggleFilled() {
        isFilled = !isFilled;

        generateData();
    }

    private void togglePointColor() {
        pointsHaveDifferentColor = !pointsHaveDifferentColor;

        generateData();
    }

    private void setCircles() {
        shape = ValueShape.CIRCLE;

        generateData();
    }

    private void setSquares() {
        shape = ValueShape.SQUARE;

        generateData();
    }

    private void setDiamonds() {
        shape = ValueShape.DIAMOND;

        generateData();
    }

    private void toggleLabels() {
        hasLabels = !hasLabels;

        if (hasLabels) {
            hasLabelForSelected = false;
            chart.setValueSelectionEnabled(hasLabelForSelected);
        }

        generateData();
    }

    private void toggleLabelForSelected() {
        hasLabelForSelected = !hasLabelForSelected;

        chart.setValueSelectionEnabled(hasLabelForSelected);

        if (hasLabelForSelected) {
            hasLabels = false;
        }

        generateData();
    }

    private void toggleAxes() {
        hasAxes = !hasAxes;

        generateData();
    }

    private void toggleAxesNames() {
        hasAxesNames = !hasAxesNames;

        generateData();
    }

    /**
     * To animate values you have to change targets values and then call {@link Chart#startDataAnimation()}
     * method(don't confuse with View.animate()). If you operate on data that was set before you don't have to call
     * {@link LineChartView#setLineChartData(LineChartData)} again.
     */
    private void prepareDataAnimation() {
        for (Line line : data.getLines()) {
            for (PointValue value : line.getValues()) {
                // Here I modify target only for Y values but it is OK to modify X targets as well.
                value.setTarget(value.getX(), (float) Math.random() * 100);
            }
        }
    }

    @Override
    public void onClick(View v) {
        {
            switch (v.getId()) {
                case R.id.iv_title_back:
                    finish();
                    break;
                case R.id.xuetangdetail_layout_time:

                    timePopup.showAsDropDown(ivgLayout);

                    setInitPopup();
                    timeTV.setTextColor(mContext.getResources().getColor(R.color.light_blue));
                    timeIV.setImageResource(R.mipmap.tab_arrow_pre);
                    break;
                case R.id.xuetangdetail_layout_cat:

                    kindPopup.showAsDropDown(ivgLayout);

                    setInitPopup();
                    catTV.setTextColor(mContext.getResources().getColor(R.color.light_blue));
                    catIV.setImageResource(R.mipmap.tab_arrow_pre);
                    break;
//                case R.id.timeline_btn_day:
//                    timePopup.dismiss();
//                    ;
//                    break;
                case R.id.timeline_btn_week:
                    timePopup.dismiss();
                    ;
                    break;
                case R.id.timeline_btn_month:
                    timePopup.dismiss();
                    ;
                    break;
                case R.id.timeline_view_whole:
                    if (timePopup != null) {
                        timePopup.dismiss();
                    }
                    break;
                case R.id.kind_view_whole:
                    if (kindPopup != null) {
                        kindPopup.dismiss();
                    }
                    break;
            }
        }

    }

    private class ValueTouchListener implements LineChartOnValueSelectListener {

        @Override
        public void onValueSelected(int lineIndex, int pointIndex, PointValue value) {
            Toast.makeText(XuetangDetailActivity.this, "Selected: " + value, Toast.LENGTH_SHORT).show();
        }

        @Override
        public void onValueDeselected() {
            // TODO Auto-generated method stub

        }

    }
}
